package com.bjpowernode.crm.settings.web.interceptor;

import com.bjpowernode.crm.commons.contants.Contants;
import com.bjpowernode.crm.settings.model.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        // 请求到达目标资源之前执行
//        如果用户没有登录成功，则返回登录首页
        //        判断是否存在user对象
        HttpSession session = httpServletRequest.getSession();
//        获取是否有一个user对象
        User user = (User)session.getAttribute(Contants.SESSION_USER);
//        判断user是否为空
        if(user == null){
//            如果user为空，表示没有登录，或者登录过期
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()); // 当手动重定向的时候，必须带上项目的名称
            return false;
        }
//        如果用户登录成功，则放行
//        返回true的时候放行，返回false的时候拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
